package com.oujia.cloud.cloudcommon.bean.xinge;

import com.oujia.cloud.cloudcommon.api.APIResultEnum;
import com.oujia.cloud.cloudcommon.bean.exception.ServiceException;
import com.oujia.cloud.cloudcommon.util.DateUtils;
import com.oujia.cloud.cloudcommon.util.JSONUtil;
import com.tencent.xinge.*;
import lombok.extern.log4j.Log4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Log4j
public class XinGeUtils {

    private XinGeUtils() {
    }

    private static final XinGeUtils instance = new XinGeUtils();

    private static Long androidAccessId;

    private static String androidSecretKey;

    private static Long iosAccessId;

    private static String iosSecretKey;
    private static Style style = new Style(3, 1, 0, 1, 0);
    private static TimeInterval acceptTime = new TimeInterval(0, 0, 23, 59);

    public static Long getAndroidAccessId() {
        return androidAccessId;
    }

    @Value("${xinge.android.accessId}")
    public void setAndroidAccessId(Long androidAccessId) {
        XinGeUtils.androidAccessId = androidAccessId;
    }

    public static String getAndroidSecretKey() {
        return androidSecretKey;
    }

    @Value("${xinge.android.secretKey}")
    public void setAndroidSecretKey(String androidSecretKey) {
        XinGeUtils.androidSecretKey = androidSecretKey;
    }

    public static Long getIosAccessId() {
        return iosAccessId;
    }

    @Value("${xinge.ios.accessId}")
    public void setIosAccessId(Long iosAccessId) {
        XinGeUtils.iosAccessId = iosAccessId;
    }

    public static String getIosSecretKey() {
        return iosSecretKey;
    }


    private static Message messageAndroid = new Message();
    private static MessageIOS messageIos = new MessageIOS();
    private static XingeApp ANDROIDAPP;
    private static XingeApp IOSAPP;

    @Value("${xinge.ios.secretKey}")
    public void setIosSecretKey(String iosSecretKey) {
        XinGeUtils.iosSecretKey = iosSecretKey;
    }

    public static XinGeUtils getInstance() {
        if (ANDROIDAPP == null) {
            ANDROIDAPP = new XingeApp(androidAccessId, androidSecretKey);
        }
        if (IOSAPP == null) {
            IOSAPP = new XingeApp(iosAccessId, iosSecretKey);
        }
        return instance;
    }

    /**
     * 标签推送
     *
     * @param dto
     * @param tagList
     * @return
     */
    public Map pushTags(MsgInfoDTO dto, List<String> tagList) {
        setMsg(dto);
        Map map = new HashMap();
        JSONObject ret = ANDROIDAPP.pushTags(0, tagList, "OR", messageAndroid);
        log.info("安卓标签推送返回:" + JSONUtil.toJson(ret));
        map.put("androidPushId", getPushId(ret));
        ret = IOSAPP.pushTags(0, tagList, "OR", messageIos, XingeApp.IOSENV_PROD);
        log.info("ios标签推送返回:" + JSONUtil.toJson(ret));
        map.put("iosPushId", getPushId(ret));
        return map;
    }

    private String getPushId(JSONObject ret) {
        if ("0".equalsIgnoreCase(ret.get("ret_code") + "")) {
            String pushId = JSONUtil.toMap(ret.get("result") + "").get("push_id") + "";
            return pushId;
        } else {
            throw new ServiceException(APIResultEnum.XINGE_PUSH_ERR);
        }
    }

    private String getAccountPushId(JSONObject ret) {
        if ("0".equalsIgnoreCase(ret.get("ret_code") + "")) {
            String pushId = JSONUtil.toList(ret.get("result") + "", Long.class).get(0) + "";
            return pushId;
        } else {
            throw new ServiceException(APIResultEnum.XINGE_PUSH_ERR);
        }
    }

    /**
     * 账号推送
     *
     * @param dto
     * @param accountList
     * @return
     */
    public Map pushAccountList(MsgInfoDTO dto, List<String> accountList) {
        setMsg(dto);
        Map map = new HashMap();
        JSONObject ret = ANDROIDAPP.pushAccountList(0, accountList, messageAndroid);
        map.put("androidPushId", getAccountPushId(ret));
        log.info("安卓账号推送返回:" + JSONUtil.toJson(ret));
        ret = IOSAPP.pushAccountList(0, accountList, messageIos, XingeApp.IOSENV_PROD);
        map.put("iosPushId", getAccountPushId(ret));
        log.info("ios账号推送返回:" + JSONUtil.toJson(ret));
        return map;
    }

    public void setMsg(MsgInfoDTO dto) {
        messageAndroid.setType(Message.TYPE_NOTIFICATION);
        messageAndroid.setStyle(style);
        messageAndroid.addAcceptTime(acceptTime);
        messageIos.setType(MessageIOS.TYPE_APNS_NOTIFICATION);
        messageIos.addAcceptTime(acceptTime);
        messageIos.setExpireTime(86400);
        messageIos.setCategory("INVITE_CATEGORY");
        messageAndroid.setContent(dto.getContent());
        messageAndroid.setTitle(dto.getTitle());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", dto.getTitle());
        jsonObject.put("body", dto.getContent());
        messageIos.setAlert(jsonObject);
        //是消息中心或者弹窗 需要自定义参数
        if (dto.getMsgType() == 1 || dto.getMsgType() == 2) {
            Map map = JSONUtil.toMap(JSONUtil.toJson(dto));
            messageIos.setCustom(map); //自定义参数
            messageAndroid.setCustom(map); //自定义参数
        }
        // 最大取值14天
        if (dto.getPushEndTime() != null && dto.getPushEndTime().compareTo(dto.getPushStartTime()) > 0) {
            Date dateEnd = DateUtils.parseDate(DateUtils.format(dto.getPushEndTime(), DateUtils.DATE_PATTERN));
            Date dateStart = DateUtils.parseDate(DateUtils.format(dto.getPushStartTime(), DateUtils.DATE_PATTERN));
            Long dateCount = DateUtils.getDiffDay(dateStart, dateEnd);
            if (dateCount > 0) {
                if (dateCount >= 14) {
                    dateCount = 14L;
                }
                messageAndroid.setLoopInterval(dateCount.intValue());
                messageAndroid.setLoopTimes(1);
            }
        }
    }

    /**
     * 取消定时任务
     *
     * @param map
     * @return
     */
    public JSONObject demoCancelTimingPush(Map map) {
        JSONObject ret1 = IOSAPP.cancelTimingPush(map.get("iosPushId") + "");
        log.info("iOS取消定时任务:" + ret1);
        JSONObject ret2 = ANDROIDAPP.cancelTimingPush(map.get("androidPushId") + "");
        log.info("安卓取消定时任务:" + ret2);
        return ret1;
    }

    /**
     * 查询标签
     *
     * @return
     */
    public List<String> demoQueryTags() {
        JSONObject ret = IOSAPP.queryTags();
        log.info("ISO获取的标签为:" + ret);
        if (ret != null && ("0".equalsIgnoreCase(ret.get("ret_code") + ""))) {
            return JSONUtil.toList(JSONUtil.toMap(ret.get("result") + "").get("tags") + "", String.class);
        }
        return null;
    }
}
